public class Solution200 {
    boolean[][] visited;

    public int numIslands(char[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        visited = new boolean[m][n];
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1' && !visited[i][j]) {
                    res++;
                    dfs(grid, i, j);
                }
            }
        }
        return res;
    }

    void dfs(char[][] grid, int i, int j) {
        if (visited[i][j] || grid[i][j] == '0') {
            return;
        }
        visited[i][j] = true;
        if (i > 0) {
            dfs(grid, i - 1, j);
        }
        if (i < grid.length - 1) {
            dfs(grid, i + 1, j);
        }
        if (j > 0) {
            dfs(grid, i, j - 1);
        }
        if (j < grid[0].length - 1) {
            dfs(grid, i, j + 1);
        }
    }
}
